<?php

class authentication {
	private $connection, $loginurl;
	public $login_error;
	
	function __construct($loginurl) {
		$this->connection = pg_connect("
			host=localhost 
			port=5432 
			dbname=headlights 
			user=".PG_USER."
			password=".PG_PASS."
		") or die ("FATAL: Couldn't connect to database");
		
		$this->loginurl = $loginurl;

		if(!$this->isAuthorized()) {
			if($_POST['username'] && $_POST['password']) {
				if(!$this->isBanned()) {
					$username = pg_escape_string($_POST['username']);
					$password = pg_escape_string($_POST['password']);
					$sql = "SELECT * FROM users WHERE username='".$username."'
							AND password='".$password."'";

					$res = pg_query($sql);
					if(pg_num_rows($res) == 1) {
						$this->authorize();
					} else {
						$this->login_error = "Feil brukernavn eller passord";
						$this->printForm($this->login_error);
					}
				}
			}
		} else if($_GET['logout']) {
			$this->logout();
		}
	}

	public function isAuthorized() {
		if(isset($_SESSION['auth']) == 1) {
			return true;
		} else {
			return false;
		}
	}

	private function isBanned() {
		return false;
	}	

	private function authorize() {
		$_SESSION['auth'] = 1;
		$_SESSION['errors'] = 0;
	}	

	public function logout() {
		unset($_SESSION['auth']);
	}
	
	public function printForm($msg) {
		$login_error = "<p class=\"error\">$msg</p>";
		include_once('inc/login.php');
	}

	private function errorMsg($msg) {

	}

}

?>

